<?php

use Core\AdminController;
use Models\Cashier;

class CashierController extends AdminController
{
	public function __construct()
	{
		parent::__construct();
		$this->lang->load('admin_cashier', $this->session->admin_language);
	}
	public function index()
	{
		$cashier = new Cashier();

		$page = $cashier
		->order_by('id desc')
		->paginate(20);

		$this->load->view('admin/cashier/index', [
			'page' => $page,
		]);
	}

	public function set_status($id)
	{
		$cashier = (new Cashier)->find($id);
		if (!$cashier) {
			return $this->response(['error' => 'not found'], 404);
		}

		$cashier['status'] = $this->input->post('status');
		$cashier->update();

		return $this->response([
				'error' => 'success'
			]);
	}

	public function create()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', '用户民', 'required|is_unique[cashiers.username]')
		->set_rules('password', '密码', 'required');
		if ($this->form_validation->run()) {
			$cashier = new Cashier();
			$cashier->load($this->input->post());
			$cashier['password'] = encrypt($cashier['password']);
			$cashier['create_time'] = date('Y-m-d H:i:s');
			$cashier->add();

			return $this->response(['error' => 'success']);
		}

		return $this->response(['error' => $this->form_validation->error_string()], 422);
	}

	public function reset_password($id)
	{
		$password = $this->input->post('password');
		if (!$password) {
			return $this->response(['error' => $this->lang->line('请输入密码')], 422);
		}

		$cashier = (new Cashier())->find($id);
		if (!$cashier) {
			return $this->response(['error' => 'not found'], 404);
		}

		$cashier['password'] = encrypt($password);
		$cashier->update();

		return $this->response(['error' => 'success']);
	}
}